<!-- 最初的文章统计页面，目前未使用 -->
<template>
  <div>
    <div class="bg-white h-auto my-2 mb-2 py-2">
      <BasicForm @register="registerForm" @submit="handleSubmit" />
    </div>
    <div class="flex">
      <div class="flex flex-col pr-4 w-1/2">
        <BasicTable
          @register="registerTable"
          :can-resize="true"
          :bordered="true"
          :striped="true"
          :loading="false"
          :data-source="authorsData.authors"
        >
          <template #toolbar>
            <a-button @click="aoaToAuthorExcel"> 导出 </a-button>
          </template>
          <template #authorName="{ record }">
            <span style="cursor: pointer" @click="onArticlesByAuthor(record.name)">
              {{ record.name }}
            </span>
          </template>
        </BasicTable>
      </div>
      <div class="flex flex-col pr-4 w-1/2">
        <BasicTable
          @register="registerTableDepts"
          :can-resize="true"
          :bordered="true"
          :striped="true"
          :loading="false"
          :data-source="deptsData.depts"
        >
          <template #toolbar>
            <a-button @click="aoaToDeptExcel"> 导出 </a-button>
          </template>
          <template #deptName="{ record }">
            <span style="cursor: pointer" @click="onArticlesByDept(record.name)">
              {{ record.name }}
            </span>
          </template>
        </BasicTable>
      </div>
    </div>
    <div style="width: 100%; margin-top: 8px">
      <div ref="chartRef" :style="{ height, width }"></div>
    </div>
    <authorArticlesTable @register="registerAuthorArticlesTable" />
    <deptArticlesTable @register="registerDeptArticlesTable" />
  </div>
</template>
<script lang="ts">
  import {
    defineComponent,
    onBeforeMount,
    onUnmounted,
    reactive,
    ref,
    provide,
    Ref,
    toRaw,
  } from 'vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicForm, useForm } from '/@/components/Form/index';

  import { queryStatistics } from '/@/api/cms/statistics';
  import {
    queryTableAuthorsColumns,
    queryTableDeptsColumns,
    queryConditionFormSchema,
    authorArrHeader,
    deptArrHeader,
  } from './statistics.data';
  import { ArticleStatisticsConditionDto } from '/@/api/cms/model/statisticsModel';

  //引入子组件
  import authorArticlesTable from './authorArticlesTable.vue';
  import deptArticlesTable from './deptArticlesTable.vue';

  //使用modal弹出窗口
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import moment from 'moment';

  import { useECharts } from '/@/hooks/web/useECharts';

  import { aoaToSheetXlsx } from '/@/components/Excel';

  const { createMessage } = useMessage();

  const [registerAuthorArticlesTable, { openModal: openAuthorArticlesTable }] = useModal();
  const [registerDeptArticlesTable, { openModal: openDeptArticlesTable }] = useModal();

  export default defineComponent({
    name: 'StatisticsManagement',
    components: { BasicTable, BasicForm, authorArticlesTable, deptArticlesTable },
    props: {
      width: {
        type: String as PropType<string>,
        default: '98.7%',
      },
      height: {
        type: String as PropType<string>,
        default: 'calc(100vh - 330px)',
      },
    },
    setup() {
      //定义模块的名称，提供给子孙组件获取使用
      const moduleName = ref('文章统计');
      provide('moduleName', moduleName);

      //按作者统计文章数据
      const authorsData = reactive({
        authors: [],
      });

      //按部门统计文章数据
      const deptsData = reactive({
        depts: [],
      });

      //导出按作者统计数组数据
      let arrAuthorData = ref([]);
      function aoaToAuthorExcel() {
        console.log('导出按作者统计数据', arrAuthorData);
        // 保证data顺序与header一致
        aoaToSheetXlsx({
          data: arrAuthorData, //数组数据
          header: authorArrHeader, //表头
          filename: '按作者统计文章.xlsx', //导出的文件名
        });
      }

      //导出按作者统计数组数据
      let arrDeptData = ref([]);
      function aoaToDeptExcel() {
        console.log('导出按部门统计数据', arrDeptData);
        // 保证data顺序与header一致
        aoaToSheetXlsx({
          data: arrDeptData,
          header: deptArrHeader,
          filename: '按部门统计文章.xlsx',
        });
      }

      const chartRef = ref<HTMLDivElement | null>(null);
      const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);

      //请求接口查询条件
      let time = new Date();
      let monthNum = moment().month();
      let queryConditionDto: ArticleStatisticsConditionDto = {
        begintm: moment(time).month(monthNum).date(1).startOf('month').format('YYYY-MM-DD'), //默认当月第一天
        endtm: moment(time).month(monthNum).date(1).endOf('month').format('YYYY-MM-DD'), //默认当月最后一天
        ids: [],
        author: '',
        dept: '',
      };

      onBeforeMount(() => {
        console.log('DOM即将挂载');
        getQueryStatistics();
      });
      onUnmounted(() => {
        console.log('销毁完毕');
      });

      const [registerForm] = useForm({
        labelWidth: 80,
        schemas: queryConditionFormSchema,
        // actionColOptions: {
        //   span: 24,
        // },
      });

      const [registerTable] = useTable({
        title: '按作者统计文章',
        columns: queryTableAuthorsColumns, //表头数据
        showTableSetting: false, //是否显示表格设置
        bordered: true,
        striped: false, //斑马纹
        showIndexColumn: true,
        pagination: false,
        scroll: { y: 450 },
      });

      const [registerTableDepts] = useTable({
        title: '按部门统计文章',
        columns: queryTableDeptsColumns, //表头数据
        showTableSetting: false, //是否显示表格设置
        bordered: true,
        striped: false, //斑马纹
        showIndexColumn: true,
        pagination: false,
        scroll: { y: 450 },
      });

      /**
       * 表单提交按钮事件
       */
      function handleSubmit(values: any) {
        console.log(values);
        let date = values.beginEndtm;
        console.log('date', date);
        let beginDate;
        let endDate;
        for (let i = 0; i < date.length; i++) {
          beginDate = date[0];
          endDate = date[1];
        }
        // console.log('beginDate', beginDate);
        // console.log('endDate', endDate);
        queryConditionDto.begintm = beginDate;
        queryConditionDto.endtm = endDate;
        queryConditionDto.ids = values.ids;
        getQueryStatistics();
      }

      /**
       * 统计查询
       */
      async function getQueryStatistics() {
        if (authorsData.authors.length > 0) {
          authorsData.authors = [];
        }
        if (deptsData.depts.length > 0) {
          deptsData.depts = [];
        }
        queryStatistics(queryConditionDto)
          .then((res) => {
            console.log('res', res);
            //处理返回数据
            if (res.authors != null) {
              res.authors.forEach((val) => {
                let author = {
                  name: val.name,
                  value: val.count,
                };
                authorsData.authors.push(author);
              });
            }
            if (res.depts != null) {
              res.depts.forEach((val) => {
                let dept = {
                  name: val.name,
                  value: val.count,
                };
                deptsData.depts.push(dept);
              });
            }

            //导出按作者统计数据
            arrAuthorData = authorsData.authors.map((item) => {
              return Object.keys(item).map((key) => item[key]);
            });
            //导出按部门统计数据
            arrDeptData = deptsData.depts.map((item) => {
              return Object.keys(item).map((key) => item[key]);
            });

            setOptions({
              // backgroundColor: '#0f375f',
              backgroundColor: '#fff',
              title: [
                {
                  text: '按作者统计文章',
                  left: '1%',
                  top: '1%',
                  textStyle: {
                    // color: '#fff',
                    color: '#000',
                    fontSize: 14,
                  },
                },
                {
                  text: '按部门统计文章',
                  left: '51%',
                  top: '1%',
                  textStyle: {
                    // color: '#fff',
                    color: '#000',
                    fontSize: 14,
                  },
                },
              ],
              tooltip: {
                formatter: '{b}:{c} ({d}%)',
              },
              series: [
                {
                  name: '按作者统计文章',
                  type: 'pie',
                  radius: '50%',
                  center: ['25%', '45%'],
                  data: toRaw(authorsData.authors),
                  color: [
                    '#5470c6',
                    '#91cc75',
                    '#fac858',
                    '#ee6666',
                    '#73c0de',
                    '#3ba272',
                    '#fc8452',
                    '#9a60b4',
                    '#ea7ccc',
                  ],
                  labelLine: { show: true },
                  label: {
                    show: true,
                    formatter: '{b}:{c} ({d}%)',
                    // color: '#B1B9D3',
                  },
                },
                {
                  name: '按部门统计文章',
                  type: 'pie',
                  radius: '50%',
                  center: ['75%', '45%'],
                  labelLine: { show: true },
                  data: toRaw(deptsData.depts),
                  color: [
                    '#5470c6',
                    '#91cc75',
                    '#fac858',
                    '#ee6666',
                    '#73c0de',
                    '#3ba272',
                    '#fc8452',
                    '#9a60b4',
                    '#ea7ccc',
                  ],
                  label: {
                    show: true,
                    formatter: '{b}:{c} ({d}%)',
                    // color: '#B1B9D3',
                  },
                },
              ],
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 按作者统计文章：点击作者获取作者名称，打开指定作者统计文章窗口
       */
      function onArticlesByAuthor(author) {
        // console.log('作者：' + author);
        queryConditionDto.author = author;
        //使用props传递数据至子组件，在data参数中指定
        openAuthorArticlesTable(true, { op: '指定作者文章统计', condition: queryConditionDto });
      }

      /**
       * 按部门统计文章：点击部门获取部门名称，打开指定部门统计文章窗口
       */
      function onArticlesByDept(dept) {
        // console.log('部门：' + dept);
        queryConditionDto.dept = dept;
        //使用props传递数据至子组件，在data参数中指定
        openDeptArticlesTable(true, { op: '指定部门文章统计', condition: queryConditionDto });
      }

      return {
        registerForm,
        registerTable,
        registerTableDepts,
        authorsData,
        deptsData,
        handleSubmit,
        onArticlesByAuthor,
        onArticlesByDept,
        registerAuthorArticlesTable,
        registerDeptArticlesTable,

        chartRef,

        aoaToAuthorExcel,
        aoaToDeptExcel,
      };
    },
  });
</script>
